package com.veer.shop.utils;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.veer.shop.config.BnBuilderConfig;

/**
 * 实体编号生成器
 * 
 * @author WangBin
 * 2020年10月19日-下午3:12:43
 */
@Component
public class BnBuilderUtil {
	@Autowired
	private RedisUtil redisUtil;
	
	public String generate(String objectKey)
	{
		String bn = "";
		
		// 生成编号对象key不可为空
		if(StringUtils.isEmpty(objectKey))return bn;
		// 编号格式配置不可为空
		if(!BnBuilderConfig.BN_BUILDER_FORMAT_MAP.containsKey(objectKey)) return bn;
		// 编号格式
		bn = BnBuilderConfig.BN_BUILDER_FORMAT_MAP.get(objectKey).get(0);
		// redis 编号计数的键 = 配置的前缀 + 年月日（20200105）
		String curDate = DateTimeUtil.getFormatDate("yyMMdd");
		String redisCountKey = BnBuilderConfig.BN_BUILDER_FORMAT_MAP.get(objectKey).get(1) + curDate; 
		
		// 配置时间日期格式
		String dateRegx = "\\[([a-zA-Z])+\\]";
		Pattern datePattern = Pattern.compile(dateRegx);
		Matcher dateMatcher = datePattern.matcher(bn);
		String dateRp = "";
		if(dateMatcher.find()) {
			dateRp = DateTimeUtil.getFormatDate(dateMatcher.group(0));
			bn = bn.replaceAll(dateRegx, "dateRp");
			dateRp = dateRp.replace("[", "").replace("]", "");
		}
		
		// 匹配自增计数
		String countRegx = "\\[[0-9]+\\]";
		Pattern countPattern = Pattern.compile(countRegx);
		Matcher countMatcher = countPattern.matcher(bn);
		String countRp = "";
		if(countMatcher.find()) {
			countRp = countMatcher.group(0);
			bn = bn.replaceAll(countRegx, "countRp");
			countRp = countRp.replace("[", "").replace("]", "");
		}

		// 获取缓存中的计数个数,key不存在则新建并赋值1
		int count = 1;
		if(redisUtil.hasKey(redisCountKey)) {
			count = Integer.valueOf(redisUtil.get(redisCountKey)) + 1;
		} else {
			redisUtil.set(redisCountKey, String.valueOf(count));
			// 设置过期时间
			redisUtil.expire(redisCountKey, BnBuilderConfig.REDIS_BN_COUNTER_LIFE_TIME, TimeUnit.SECONDS);
		}
		
		redisUtil.set(redisCountKey, String.valueOf(count));

		// 组装获取编号
		bn = bn.replace("dateRp", dateRp).replace("countRp", String.format("%0" + countRp + "d", count));
		
		return bn;
	}
}
